package com.tanhua.commons.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.commons.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class AliyunSmsTemplate {

    @Autowired
    private AliyunSmsProperties smsProperties;

    public Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(smsProperties.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(smsProperties.getAccessKeySecret());
        // 访问的域名
        config.endpoint = smsProperties.getEndpoint();
        return new Client(config);
    }
    public String sendSms(String mobile) {
        try {
            int code = RandomUtils.nextInt(100000, 1000000);
            String smsCode = "{\"code\": \"" + code + "\"}";

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam(smsCode);

            SendSmsResponse sendSmsResponse = createClient().sendSms(sendSmsRequest);
            String responseCode = sendSmsResponse.getBody().getCode();
            if ("OK".equals(responseCode)) {
                return String.valueOf(code);
            } else {
                log.warn("发送短信失败，错误码：{}，错误消息：{}", responseCode, sendSmsResponse.getBody().getMessage());
                return null;
            }
        } catch (Exception e) {
            log.error("发送短信失败", e);
            return null;
        }
    }

}
